package com.csglxt.view.action;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.csglxt.base.BaseAction;
import com.csglxt.domain.User;
import com.csglxt.utils.QueryHelper;
import com.opensymphony.xwork2.ActionContext;

/**
 * 
 * @ClassName: UserAction
 * @Description: 用户控制器
 * @author Delver_Si
 * @date 2015-5-29 上午12:00:08
 * 
 */

@Controller
@Scope("prototype")
@SuppressWarnings("serial")
public class UserAction extends BaseAction<User> {

    private String rePassword;

    public String getRePassword() {
        return rePassword;
    }

    public void setRePassword(String rePassword) {
        this.rePassword = rePassword;
    }

    // 模糊查询参数名
    private String Searchname;

    public String getSearchname() {
        return Searchname;
    }

    public void setSearchname(String searchname) {
        Searchname = searchname;
    }

    // 登录界面
    public String loginUI() {
        return "loginUI";

    }

    // 登录
    public String login() {
        if (getCurrentUser() != null) {
            return "toHome";
        }

        if (ServletActionContext.getRequest().getMethod()
                .equalsIgnoreCase("GET")) {
            return "loginUI";
        }

        User user = userService.findByUsernameAndPassword(model);
        if (user == null) {
            addFieldError("login", "用户名或密码不正确！");
            return "loginUI";
        } else {
            getSession().put("user", user);
            return "toHome";

        }

    }

    // 资料浏览
    public String info() {
        User user = userService.getById((getCurrentUser()).getId());
        getValueStack().push(user);
        return "info";
    }

    // 修改资料
    public String editUI() {
        User user = userService.getById(model.getId());
        getValueStack().push(user);
        return "saveUI";
    }

    // 保存资料
    public String save() {
        userService.update(model);
        String view = "";

        if ("1".equals(model.getRole())
                && "1".equals(getCurrentUser().getRole())) {
            view = "toInfo";
        } else if ("2".equals(model.getRole())
                && "1".equals(getCurrentUser().getRole())) {
            view = "toList";
        } else if ("2".equals(getCurrentUser().getRole())) {
            view = "toInfo";
        }

        return view;
    }

    // 修改密码
    public String editPasswordUI() {
        User user = userService.getById(getCurrentUser().getId());
        getValueStack().push(user);
        return "savePasswordUI";
    }

    /**
     * 更新密码
     * 
     * @return
     */
    public String updatePwd() {
        if (model.getPassword().equals("")) {
            addFieldError("password", "密码不能为空");
            return "savePasswordUI";
        } else if (!rePassword.equals(model.getPassword())) {
            addFieldError("password", "两次密码不一致");
            return "savePasswordUI";
        } else {
            User user = userService.getById(getCurrentUser().getId());
            user.setPassword(DigestUtils.md5Hex(model.getPassword()));
            userService.update(user);
            return "toInfo";
        }

    }

    // 注销
    public String logout() {
        getSession().remove("user");
        return "loginUI";
    }

    /**
     * 添加员工页面
     * 
     * @return
     */
    public String addUI() {
        if (!((User) getSession().get("user")).getRole().equals("1")) {
            return "noPrivilege";
        } else {
            return "addUserUI";
        }
    }

    /**
     * 添加员工
     * 
     * @return
     */
    public String addUser() {

        if (!((User) getSession().get("user")).getRole().equals("1")) {
            return "noPrivilege";
        } else {
            User user = new User();
            user.setRole("2");
            user.setUsername(model.getUsername());
            user.setPassword(DigestUtils.md5Hex("123"));// 默认123
            user.setName(model.getName());
            user.setSex(model.getSex());
            user.setPhoneNumber(model.getPhoneNumber());
            user.setEmail(model.getEmail());
            userService.save(user);
            return "toList";
        }

    }

    /**
     * 员工列表
     * 
     * @return
     */
    public String list() {
        if (!((User) getSession().get("user")).getRole().equals("1")) {
            return "noPrivilege";
        } else {

            new QueryHelper(User.class, "u")
                    .addCondition(true, "u.role=?", "2")
                    .addOrderProperty("name", true)
                    .preparePageBean(userService, pageNum, pageSize);
            return "list";
        }
    }

    /**
     * 员工列表模糊查询
     * 
     * @return
     */
    public String Searchlist() {
        QueryHelper qureyHelper = new QueryHelper(User.class, "u")
                .addOrderProperty("name", true);
        if (Searchname != null && !Searchname.isEmpty()) {
            qureyHelper.addCondition(" u.username like ? ", "%" + Searchname
                    + "%");

        }

        qureyHelper.preparePageBean(supplierService, pageNum, pageSize);
        return "list";
    }

    /**
     * 初始化员工密码为123
     */
    public String initPassword() {
        if (!((User) getSession().get("user")).getRole().equals("1")) {
            return "noPrivilege";
        } else {
            User user = userService.getById(model.getId());
            user.setPassword(DigestUtils.md5Hex("123"));
            userService.update(user);
            return "toList";
        }
    }

    /**
     * 用户删除
     * 
     * @return
     */
    public String delete() {
        userService.delete(model.getId());
        return "toList";
    }

    /**
     * ajax 验证
     * 
     * @throws IOException
     * 
     */
    public void ajx() throws IOException {
        HttpServletResponse response = (HttpServletResponse) ActionContext
                .getContext().get(
                        org.apache.struts2.StrutsStatics.HTTP_RESPONSE);

        response.setContentType("text/html;charset=utf-8");
        User user = userService.findByUsername(model);

        if (user != null) {
            // 重点用是用print输出的数据格式是json

            response.getWriter().print("{\"success\":true,\"msg\":\"已存在\"}");
        } else {

            response.getWriter().print("{\"success\":false,\"msg\":\"\"}");
        }

    }
}
